#!/bin/bash

if [ $# -lt 7 ]; then
   echo "please input : cache_id  jar_path log_file ds_no data_date  low_rfm high_rfm"
   exit
fi

cache_id=$1
jar_path=$2
log_file=$3
ds_no=$4
data_date=$5
low=$6
high=$7

tmp_file=/tmp/cache_id_$cache_id.sql

cat >> $tmp_file << EOF

add jar $jar_path/Acrm.jar;
create temporary function acrmR as 'demo.yalatin.AcrmR';
create temporary function acrmF as 'demo.yalatin.AcrmF';
create temporary function acrmM1 as 'demo.yalatin.AcrmM1';
create temporary function acrmM2 as 'demo.yalatin.AcrmM2';
create temporary function acrmM as 'demo.yalatin.AcrmM';

INSERT INTO TABLE acrm_rfm PARTITION (cache_id='$cache_id')
 select b.customer_id, b.R,b.F,c.M, round(b.R*0.45+b.F*0.35+c.M*0.20,2) as RFM 
		from (  select a.customer_id, acrmR(to_date('$data_date'),a.tran_date) as R , acrmF(freq)  as F 
			          from (select customer_id,max(tran_date)  as tran_date,count(1) as freq from acrm_transaction where ds_no='$ds_no' group by customer_id) a) b 
			     join
 				 (  select customer_id, acrmM(sum(acrmM1(tran_type)*acrmM2(amount))) as M from acrm_transaction group by customer_id) c 
		  on b.customer_id = c.customer_id
		  where  round(b.R*0.45+b.F*0.35+c.M*0.20,2) >= $low and round(b.R*0.45+b.F*0.35+c.M*0.20,2) <= $high;
EOF

nohup $HIVE_HOME/bin/hive -f "$tmp_file" -v >$log_file 2>&1

rm $tmp_file


